package com.jiajia.study;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @Title: ReliableApplication
 * @Author zjj
 * @Package com.jiajia.study
 * @Date 2024/3/14 9:23
 * @description: 启动类
 */

@SpringBootApplication
@Slf4j
public class ReliableApplication implements ApplicationRunner {

    @Resource
    private RabbitTemplate rabbitTemplate;

    public static void main(String[] args) {
        SpringApplication.run(ReliableApplication.class, args);
    }

    @Override

    public void run(ApplicationArguments args) throws Exception {
        rabbitTemplate.setConfirmCallback(( correlationData,  ack, cause)->{
            log.info("the confirm callback data is, correlationData : {},ack:{},cause:{}",correlationData,ack,cause);
            if(ack){
                log.info("send message success");
            }else{
                log.info("send message failure,the cause is :{}",cause);
            }
        });

        rabbitTemplate.setReturnsCallback((returned)->{
            log.info("the return callback data is : {}",returned);
        });
        // 关联数据对象，如果消息发送失败，可以知道是哪条消息发送失败了
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId("1");
        rabbitTemplate.convertAndSend("confirm.exchange","confirm","hello confirm callback".getBytes(StandardCharsets.UTF_8),correlationData);
        rabbitTemplate.convertAndSend("confirm.exchange","confirm1","hello return callback".getBytes(StandardCharsets.UTF_8),correlationData);
        log.info("send success ===========================");
    }
}
